package demo.gateway.metric;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class MetricsReporter {

    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(MetricsReporter.class);

    private final GatewayMetricsCollector metricsCollector;

    public MetricsReporter(GatewayMetricsCollector metricsCollector) {
        this.metricsCollector = metricsCollector;
    }

    @Scheduled(fixedRate = 60000) // 每分钟执行一次
    public void reportMetrics() {
        long currentTime = System.currentTimeMillis();
        long timeInterval = (currentTime - metricsCollector.lastReportTime) / 1000;

        // 计算各项指标
        double requestRate = metricsCollector.totalRequests.get() / timeInterval;
        double errorRate = metricsCollector.errorRequests.get() * 100.0 / metricsCollector.totalRequests.get();
        double avgResponseTime = calculateAverageResponseTime();

        // 打印指标日志
        log.info("Gateway Metrics Report:");
        log.info("Request Rate: {}/s", String.format("%.2f", requestRate));
        log.info("Error Rate: {}%", String.format("%.2f", errorRate));
        log.info("Average Response Time: {}ms", String.format("%.2f", avgResponseTime));
        log.info("Active Connections: {}", metricsCollector.activeConnections.get());
        log.info("Concurrent Requests: {}", metricsCollector.concurrentRequests.get());
        log.info("Total Request Bytes: {}", metricsCollector.totalRequestBytes.get());
        log.info("Total Response Bytes: {}", metricsCollector.totalResponseBytes.get());

        // 重置部分计数器
        metricsCollector.lastReportTime = currentTime;
    }

    private double calculateAverageResponseTime() {
        return metricsCollector.responseTimes.stream()
                .mapToLong(Long::longValue)
                .average()
                .orElse(0.0);
    }
}
